package com.gujiangbo.guardedsuspension;

import java.util.LinkedList;

/**
 * Guarded Suspension 设计模式
 * 暂时挂起
 */
public class GuardedSuspensionQueue {

    private final LinkedList<Integer> queue = new LinkedList<>();

    private final int LIMIT = 100;

    // 插入数据
    public void offer(Integer data) throws InterruptedException {
        synchronized (this) {
            while (queue.size() >= LIMIT) {
                this.wait();
            }
            queue.addLast(data);
            this.notifyAll();
        }
    }

    // 取数据
    public Integer take() throws InterruptedException {
        synchronized (this) {
            while (queue.isEmpty()) {
                this.wait();
            }
            this.notifyAll();
            return queue.removeFirst();
        }
    }

    //获取linked size
    public int getSize() {
        return queue.size();
    }


}
